package com.hl.apple.myapplication;


import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Method;

import android.app.Activity;
import android.content.Context;
import android.graphics.BitmapFactory;
import android.graphics.PixelFormat;
import android.graphics.drawable.BitmapDrawable;
import android.hardware.Camera;
import android.hardware.Camera.AutoFocusCallback;
import android.hardware.Camera.Parameters;
import android.hardware.Camera.PictureCallback;
import android.hardware.Camera.ShutterCallback;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;


@SuppressWarnings("deprecation")
public class PhotographActivity extends Activity implements OnClickListener, SurfaceHolder.Callback {
    private SurfaceView surfaceView;
    private Camera camera;
    private Camera.Parameters parameters;
    private Button btn_goback, btn_takephoto;
    private SurfaceHolder surfaceHolder;

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (camera != null) {
            camera.stopPreview();
            camera.release();
            camera = null;
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_testcamera);
        initView();
    }

    @Override
    protected void onResume() {
        super.onResume();
        initCamera();
    }

    private void initView() {
        btn_goback = (Button) findViewById(R.id.btn_goback);
        btn_goback.setOnClickListener(this);
        btn_takephoto = (Button) findViewById(R.id.btn_takephoto);
        btn_takephoto.setOnClickListener(this);

        surfaceView = (SurfaceView) findViewById(R.id.surfaceView);
        surfaceView.setFocusable(true);
        surfaceView.setOnClickListener(this);
        surfaceView.setBackgroundColor(TRIM_MEMORY_BACKGROUND);
        surfaceHolder = surfaceView.getHolder();
        surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        surfaceHolder.setKeepScreenOn(true);
        surfaceHolder.setFixedSize(400, 300);
        surfaceHolder.addCallback(this);
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        // TODO Auto-generated method stub
        camera.stopPreview();
        camera.release();
        camera = null;

    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        // TODO Auto-generated method stub
        try {
            camera.setPreviewDisplay(surfaceHolder);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        // 实现自动对焦
        camera.autoFocus(new AutoFocusCallback() {
            @Override
            public void onAutoFocus(boolean success, Camera camera) {
                if (success) {
//                    camera.cancelAutoFocus();// 只有加上了这一句，才会自动对焦
                    doAutoFocus();
                }
            }
        });
    }

    // 相机参数的初始化设置
    private void initCamera() {
        if (null == camera) {
            camera = Camera.open();
        }
        parameters = camera.getParameters();
        parameters.setPictureFormat(PixelFormat.JPEG);
        parameters.setFlashMode(Parameters.FLASH_MODE_TORCH);
        if (!Build.MODEL.equals("KORIDY H30")) {
            parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);// 1连续对焦
        } else {
            parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
        }
        camera.setParameters(parameters);
        setDispaly(camera);
        camera.startPreview();
        camera.cancelAutoFocus();// 2如果要实现连续的自动对焦，这一句必须加上
    }

    // 控制图像的正确显示方向
    private void setDispaly(Camera camera) {
        if (Integer.parseInt(Build.VERSION.SDK) >= 8) {
            setDisplayOrientation(camera, -90);
        } else {
            parameters.setRotation(-90);
        }

    }

    // 实现的图像的正确显示
    private void setDisplayOrientation(Camera camera, int i) {
        Method downPolymorphic;
        try {
            downPolymorphic = camera.getClass().getMethod("setDisplayOrientation", new Class[]{int.class});
            if (downPolymorphic != null) {
                downPolymorphic.invoke(camera, new Object[]{i});
            }
        } catch (Exception e) {
            Log.e("Came_e", "图像出错");
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.surfaceView:
                doAutoFocus();
                break;
            case R.id.btn_takephoto:
                takePicture();
                break;
            case R.id.btn_goback:
                finish();
                break;
            default:
                break;
        }
    }

    // handle button auto focus
    private void doAutoFocus() {
        parameters = camera.getParameters();
        parameters.setFocusMode(Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
        camera.setParameters(parameters);
        camera.autoFocus(new AutoFocusCallback() {
            @Override
            public void onAutoFocus(boolean success, Camera camera) {
                if (success) {
                    camera.cancelAutoFocus();// 只有加上了这一句，才会自动对焦。
                    if (!Build.MODEL.equals("KORIDY H30")) {
                        parameters = camera.getParameters();
                        parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);// 1连续对焦
                        camera.setParameters(parameters);
                    } else {
                        parameters = camera.getParameters();
                        parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
                        camera.setParameters(parameters);
                    }
                }
            }
        });
    }

    private void takePicture() {
        camera.takePicture(shutterCallback, rawCallback, jpegCallback);
    }

    // define shutterCallback
    ShutterCallback shutterCallback = new ShutterCallback() {
        public void onShutter() {
            // TODO Do something when the shutter closes.
        }
    };

    PictureCallback rawCallback = new PictureCallback() {
        public void onPictureTaken(byte[] data, Camera camera) {
            // TODO Do something with the image RAW data.
        }
    };

    // stroe the picture in format jpeg
    PictureCallback jpegCallback = new PictureCallback() {
        public void onPictureTaken(byte[] data, Camera camera) {
            // Save the image JPEG data to the SD card
            FileOutputStream outStream = null;
            try {
                //修改图片路径和名称
                String tempFilename = String.valueOf(System.currentTimeMillis()) + ".jpg";
//                File dir = new File(sdCard.getAbsolutePath() + "/DCIM/Camera/");
//                if (!folder.isDirectory()) {
//                    folder.mkdirs();
//                }
//                String path = Constants.CACHE_FOLDER + File.separator + tempFilename;
                outStream = new FileOutputStream(AppConstant.HEAD_PHOTO_PATH);
                outStream.write(data);
                outStream.flush();
                outStream.close();
                surfaceView.setBackgroundDrawable(new BitmapDrawable(BitmapFactory.decodeByteArray(data, 0, data.length)));
            } catch (FileNotFoundException e) {
                Log.e("TAG", "File Note Found", e);
            } catch (IOException e) {
                Log.e("TAG", "IO Exception", e);
            }
        }
    };
}
